
import 'dart:async';
import 'dart:math';

import 'package:audio_session/audio_session.dart';
import 'package:flutter/cupertino.dart';
import 'package:just_audio/just_audio.dart';

class AudioTool{

  static final player = AudioPlayer(
    // Handle audio_session events ourselves for the purpose of this demo.
    handleInterruptions: false,
    androidApplyAudioAttributes: false,
    handleAudioSessionActivation: false,
  );

  static final _filters = [];
  //过滤
  static void addFilter(String f){
    _filters.add(f);
  }
  static void removeFilter(String f,{Duration? duration}){
    if(duration != null){
      Future.delayed(duration).then((value){
        _filters.remove(f);
      });
    }else{
      _filters.remove(f);
    }
  }

  static void play(String url,{filter}){
    if(filter != null){
      var c = _filters.contains(filter);
      if(c){
        return;
      }
    }
    AudioSession.instance.then((audioSession) async {
      // This line configures the app's audio session, indicating to the OS the
      // type of audio we intend to play. Using the "speech" recipe rather than
      // "music" since we are playing a podcast.
      await audioSession.configure(const AudioSessionConfiguration.speech());
      // Listen to audio interruptions and pause or duck as appropriate.
      _handleInterruptions(audioSession);
      // Use another plugin to load audio to play.
      // "https://s3.amazonaws.com/scifri-episodes/scifri20181123-episode.mp3"
      if(url.startsWith("http")){
        await player.setUrl(url);
      }else{
        await player.setAsset(url);
      }
      //播放 设置状态
      var pf = player.play();
      // pf.then((value){
      //   player.dispose();
      // });
    });
  }

  //监听打断信息
  static void _handleInterruptions(AudioSession audioSession) {
    // just_audio can handle interruptions for us, but we have disabled that in
    // order to demonstrate manual configuration.
    bool playInterrupted = false;
    audioSession.becomingNoisyEventStream.listen((_) {
      debugPrint('AudioTool ===================== PAUSE');
      player.pause();
    });
    player.playingStream.listen((playing) {
      playInterrupted = false;
      if (playing) {
        audioSession.setActive(true);
      }
    });
    audioSession.interruptionEventStream.listen((event) {
      debugPrint('AudioTool ===================== interruption begin: ${event.begin}');
      debugPrint('AudioTool ===================== interruption type: ${event.type}');
      if (event.begin) {
        switch (event.type) {
          case AudioInterruptionType.duck:
            if (audioSession.androidAudioAttributes!.usage ==
                AndroidAudioUsage.game) {
              player.setVolume(player.volume / 2);
            }
            playInterrupted = false;
            break;
          case AudioInterruptionType.pause:
          case AudioInterruptionType.unknown:
            if (player.playing) {
              player.pause();
              playInterrupted = true;
            }
            break;
        }
      } else {
        switch (event.type) {
          case AudioInterruptionType.duck:
            player.setVolume(min(1.0, player.volume * 2));
            playInterrupted = false;
            break;
          case AudioInterruptionType.pause:
            if (playInterrupted) player.play();
            playInterrupted = false;
            break;
          case AudioInterruptionType.unknown:
            playInterrupted = false;
            break;
        }
      }
    });
    audioSession.devicesChangedEventStream.listen((event) {
      debugPrint('AudioTool ===================== Devices added: ${event.devicesAdded}');
      debugPrint('AudioTool ===================== Devices removed: ${event.devicesRemoved}');
    });
  }




}
